package com.foreverwin.mes.meapi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.meapi.mapper.WorkCenterMapper;
import com.foreverwin.mes.meapi.model.WorkCenter;
import com.foreverwin.mes.meapi.service.WorkCenterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Syngna
 * @since 2020-01-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkCenterServiceImpl extends ServiceImpl<WorkCenterMapper, WorkCenter> implements WorkCenterService {


    @Autowired
    private WorkCenterMapper workCenterMapper;

    @Override
    public Page<WorkCenter> selectPage(FrontPage<WorkCenter> frontPage, WorkCenter workCenter) {
        EntityWrapper<WorkCenter> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(workCenter);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<WorkCenter> list(WorkCenter workCenter) {
        EntityWrapper<WorkCenter> queryWrapper = new EntityWrapper<WorkCenter>();
        queryWrapper.setEntity(workCenter);
        Locale locale = LocaleContextHolder.getLocale();
        return workCenterMapper.selectList(locale.getLanguage(), queryWrapper);
    }

    @Override
    public WorkCenter getWorkCenterByWorkCenterOrResource(String workCenterOrResourceBo) {
        return workCenterMapper.selectByResource(workCenterOrResourceBo);
    }

    @Override
    public List<WorkCenter> getParent(String workCenterOrResourceBo) {
        List<WorkCenter> parentList = new ArrayList<>();
        List<WorkCenter> workCenterList = workCenterMapper.selectParentByWorkCenterOrResourceBo(workCenterOrResourceBo);
        if(workCenterList != null && workCenterList.size() > 0) {
            parentList.addAll(workCenterList);
            for(WorkCenter workCenter: workCenterList) {
                List<WorkCenter> parents = getParent(workCenter.getHandle());
                if(parents != null && parents.size() > 0) {
                    parentList.addAll(parents);
                }
            }
        }
        return parentList;
    }

    @Override
    public List<WorkCenter> getResourceParent(String resourceBo) {
        return getParent(resourceBo);
    }
}